package btanalyzer.core.config;

import java.io.OutputStream;
import java.io.PrintWriter;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringContextManager {
	
	private static final String APPCTX_CONFIG_LOCATION = 
			"classpath*:btanalyzer/core/spring/appctx.xml";
	
	private static ClassPathXmlApplicationContext appCtx = null;
	
	/**
	 * @param os output stream, where ContextManager writes stack trace of 
	 * exceptions thrown during creating application context
	 */
	public synchronized void start(OutputStream os) {
		if (appCtx != null) {
			return;
		}
		try {
			appCtx = new ClassPathXmlApplicationContext(APPCTX_CONFIG_LOCATION);
		} catch (Exception e) {
			String msg = "Error while creating new ClassPathXmlApplicationContext(" + 
					APPCTX_CONFIG_LOCATION + ")";
			PrintWriter pw = new PrintWriter(os);
			RuntimeException toThrow = new RuntimeException(msg, e);
			toThrow.printStackTrace(pw);
			throw toThrow; 
		}
	}
	
	public void start() {
		start(System.out);
	}
	
	public synchronized void stop(OutputStream os) {
		if (appCtx == null) {
			return;
		}
		try {
			appCtx.close();
			appCtx = null;
		} catch (Exception e) {
			String msg = "Error while closing ClassPathXmlApplicationContext";
			PrintWriter pw = new PrintWriter(os);
			RuntimeException toThrow = new RuntimeException(msg, e);
			toThrow.printStackTrace(pw);
			throw toThrow; 
		}
	}
	
	public void stop() {
		stop(System.out);
	}
	
	public Object getBean(String beanName) {
		return appCtx.getBean(beanName);
	}
	
	public <T> T getBean(Class<T> beanClass) {
		return appCtx.getBean(beanClass);
	}

}
